package cn.doitedu.javase.socket.demo3;

import java.io.*;
import java.net.Socket;
import java.util.Random;

public class Client {
    public static void main(String[] args) throws IOException, InterruptedException {

        // 请求服务端，建立连接
        Socket socket = new Socket("localhost", 9099);

        InputStream inputStream = socket.getInputStream();
        OutputStream outputStream = socket.getOutputStream();

        BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));


        // 先认证
        bw.write("天王盖地虎");
        bw.newLine();
        bw.flush();

        // 接收服务端的认证返回
        String line = br.readLine();
        if (!line.equals("宝塔镇河妖")) {
            bw.close();
            br.close();
            socket.close();
            System.out.println("遇到假服务器了");
            System.exit(1);
        }


        // 开始跟服务端反复交互
        for(int i = 0;i<10;i++){

            bw.write("来自客户端的数据: " + i);
            bw.newLine();
            bw.flush();

            String content = br.readLine();
            System.out.println("接收到服务端的响应: " + content);

            Thread.sleep(1000);

        }



    }
}
